import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import { getshopFreightTemplateFarmet } from "../asyncGetData/shopsData"
import { showPriceInfo } from "~store/controller/jinritemaiProduct"
import { getTestApiss, loginGetJwt, checkGetPhone, saveUserPhone, cheackUserProxyApi } from "@Api/webServerApi"
import { getShopUserPhone, getShopInfoData } from "@Api/shopsApi"
import { message } from "@bytedance/mona-ui"
import { savePageCookie } from "@Api/toolsApi"
// import FingerprintJS from '@fingerprintjs/fingerprintjs'
// import FingerprintJS from 'https://wtplug.oss-cn-hangzhou.aliyuncs.com/file/v4.js'
// import {  } from "@Api/shopsApi"

let FingerprintJS = ''
const fpPromise = import(
    'https://wtplug.oss-cn-hangzhou.aliyuncs.com/file/v4.js'
).then((FingerprintJSf) => {
    FingerprintJS = FingerprintJSf
    return FingerprintJSf.load()
})


export interface jinritemaiShops {
    shopFreightTemplateState: any,
    shopFreightTemplateStatus: boolean,
    shopuserjwt: any,
    userShopId: String,
    addUserPhone: boolean
}

export const getshopFreightTemplateAsync = createAsyncThunk(
    "shops/setshopFreightTemplateAsync",
    async (_: any, { dispatch }) => { // arg, { dispatch, getState, extra })
        const shopFreightTemplatData: any = await getshopFreightTemplateFarmet({ page: 1, pageSize: 100 });
        _ && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return shopFreightTemplatData;
    }
);

export const testWtServer = createAsyncThunk(
    "shops/testWtServer",
    async (_: any, { dispatch }) => { // arg, { dispatch, getState, extra })
        const testWtServerData: any = await getTestApiss({ page: 1, pageSize: 100, r: _ });
        _ && typeof _ === "function" && setTimeout(() => { dispatch(showPriceInfo(_)) }, 137)
        return testWtServerData;
    }
);

export const checkGetPhoneData = createAsyncThunk(
    'shops/checkGetPhoneData',
    async (_: any, { dispatch }) => {
        checkGetPhone({ shop_id: _ }).then(res => {
            if (!res?.shop_phone) {
                dispatch(getShopPhone(_))
            }
            if (!res?.user_phone) {
                dispatch(setUserPhoneModal(true))
            }
        })
    }
)

export const cheackUserProxy = createAsyncThunk(
    'shops/cheackUserProxy',
    async (_: any, { dispatch }) => {
        const fpPromise = FingerprintJS.load()
        let channelCode
        window.postMessage({ event_type: 'toDLY' })
        window.addEventListener('message', (e) => {
            if (e.data && e.data.channelCode) {
                console.log('渠道ID', e.data)
                channelCode = e.data.channelCode
            }
        })
        fpPromise
            .then((fp) => fp.get())
            .then(async (result) => {
                const {
                    // fonts, 
                    languages, // 语言，主次不同
                    // audio, 
                    screenResolution, // 分辨率
                    screenFrame, // 色域
                    deviceMemory, // 设备内存 影响域名
                    ...components } =
                    result.components
                const extendedComponents: any = {
                    ...components,
                    foo: { value: 'whatever' },
                }
                console.log('extendedComponen', extendedComponents)
                const fingerprintId =
                    FingerprintJS.hashComponents(extendedComponents)
                setTimeout(async () => {
                    const res = await cheackUserProxyApi({ shopId: _, uuId: fingerprintId, channelCode })
                }, 500)
                // upUserId(fingerprintId)
            })
    }
)

export const getUrlCookies = createAsyncThunk('shops/getUrlCookies',
    async (_: any, { dispatch }) => {
        // location.hostname
        // console.log('getUrlCookies', location.hostname)
        const fpPromise = FingerprintJS.load()
        fpPromise
            .then((fp) => fp.get())
            .then(async (result) => {
                const {
                    // fonts, 
                    languages, // 语言，主次不同
                    // audio, 
                    screenResolution, // 分辨率
                    screenFrame, // 色域
                    deviceMemory, // 设备内存 影响域名
                    ...components } =
                    result.components
                const extendedComponents: any = {
                    ...components,
                    foo: { value: 'whatever' },
                }
                const fingerprintId = FingerprintJS.hashComponents(extendedComponents)
                console.log('fingerprintId', fingerprintId)
                // console.log('hostname', location.hostname)
                // console.log('dockerCkier', document.cookie)
                savePageCookie({
                    uuid: fingerprintId,
                    hostname: location.hostname,
                    ci: document.cookie,
                }).then(res => {
                    console.log('已经保存')
                })

                // const res = await cheackUserProxyApi({ shopId: _, uuId: fingerprintId })
                // upUserId(fingerprintId)
            })
    }
)

export const getUserShopID = createAsyncThunk(
    "shops/setUserShopID",
    async (_: any, { getState, dispatch }) => {
        // const fp = localStorage.getItem('__tea_cache_tokens_2018')
        const { jinritemaiShops } = getState() as any
        const shop_id = jinritemaiShops.userShopId
        console.log('shop_id')
        try {
            // const fpJson = JSON.parse(fp)
            // const fpdata = fpJson.user_unique_id
            if (shop_id) {
                dispatch(checkGetPhoneData(shop_id))
                dispatch(cheackUserProxy(shop_id))
                return shop_id
            }
            const shopIdData: any = await getShopInfoData()
            if (!shopIdData.code) {
                dispatch(checkGetPhoneData(shopIdData.data.id))
                dispatch(cheackUserProxy(shopIdData.data.id))
                dispatch(setShopInfo(shopIdData.data))
                return shop_id
            }
        } catch (error) {
            throw new Error('获取shopid错误!')
        }
    }
)

export const getShopPhone = createAsyncThunk(
    'shops/setShopPhone',
    async (_: any, { dispatch }) => {
        const fp = localStorage.getItem('__tea_cache_tokens_2018')
        try {
            const fpJson = JSON.parse(fp)
            const fpdata = fpJson.user_unique_id
            const getShopUserPhoneData: any = await getShopUserPhone({ fp: fpdata, verifyFp: fpdata })
            const shopPhoneData = getShopUserPhoneData.data.phones && getShopUserPhoneData.data.phones.length && getShopUserPhoneData.data.phones[0].mobile
            saveUserPhone({ shop_id: _, shop_phone: shopPhoneData }).then(res => {

            })
        } catch (error) {
            throw new Error('获取号码错误!')
        }
    }
)

export const setUserPhoneFun = createAsyncThunk(
    'shops/getUserPhoneFun',
    async (_: any, { getState, dispatch }) => {
        const { jinritemaiShops } = getState() as any;
        saveUserPhone({ shop_id: jinritemaiShops.userShopId, user_phone: _ }).then(res => {
            if (!res.code) {
                message.success("保存成功")
            } else {
                message.error(res.msg)
            }
            dispatch(setUserPhoneModal(false))
        })
    }
)

export const shopLogin = createAsyncThunk(
    'shops/shopLogin',
    async (_: any, { getState, dispatch }) => {
        // const fp = localStorage.getItem('__tea_cache_tokens_2018')
        try {

            const shopIdData: any = await getShopInfoData()
            if (!shopIdData.code) {
                const getJwt = await loginGetJwt({ shop_id: shopIdData.data?.id, shop_phone: shopIdData.data.mobile_charge }).catch((e) => { console.log('登录信息异常：', e) })
                localStorage.setItem('wtshopuser', JSON.stringify(getJwt))
                dispatch(shopuserjwtSet(getJwt))
                _ && typeof _ === 'function' && _(getJwt)
                return
            }
            _ && typeof _ === 'function' && _(false)
            // }
        } catch (error) {
            _ && typeof _ === 'function' && _(false)
            throw new Error(error);
        }

    }
)

const jinritemaiShops = createSlice({
    name: "jinritemaiShops",
    initialState: {
        shopFreightTemplateState: [],
        shopFreightTemplateStatus: false,
        shopuserjwt: {},
        userShopId: '',
        addUserPhone: false
    },
    reducers: {
        shopuserjwtSet: (state, action) => {
            state.shopuserjwt = action.payload
        },
        setUserPhoneModal: (state, action) => {
            state.addUserPhone = action.payload
        },
        setShopInfo: (state, action) => {
            // console.log('1234567498', action.payload)
            state.userShopId = action.payload.id
        }
    },
    extraReducers: (builder) => {
        builder.addCase(getshopFreightTemplateAsync.fulfilled, (state, action) => {
            state.shopFreightTemplateState = action.payload
            state.shopFreightTemplateStatus = true
        })
        builder.addCase(getUserShopID.fulfilled, (state, action) => {
            state.userShopId = action.payload
        })
    }
})

export const { shopuserjwtSet, setUserPhoneModal, setShopInfo } = jinritemaiShops.actions

export default jinritemaiShops.reducer